package auth

import (
	"github.com/gin-gonic/gin"
	v1 "go_api/app/http/controllers/api/v1"
	"go_api/app/requests"
	"go_api/pkg/auth"
	"go_api/pkg/jwt"
	"go_api/pkg/response"
)

type LoginController struct {
	v1.BaseApiController
}

// LoginByPhone 手机登录
func (lc *LoginController) LoginByPhone(c *gin.Context) {
	// 1.验证表单
	request := requests.LoginByPhoneRequest{}
	if ok := requests.ValidateErrs(c, &request, requests.LoginByPhone); !ok {
		return
	}

	// 2.尝试登录
	user, err := auth.LoginByPhone(request.Phone)
	if err != nil {
		// 失败，显示错误提示
		response.Error(c, err, "账号补存在或验证码错误")
	}

	// 登录成功
	token := jwt.NewJWT().IssueToken(user.GetStringID(), user.Name)

	response.Data(c, gin.H{
		"access_token": token,
	})
}

// LoginByPassword 多种方式登录，支持手机号、email 和用户名
func (lc *LoginController) LoginByPassword(c *gin.Context) {
	// 1.验证表单
	request := requests.LoginByPasswordRequest{}
	if ok := requests.ValidateErrs(c, &request, requests.LoginByPassword); !ok {
		return
	}

	// 2.尝试登录
	user, err := auth.Attempt(request.LoginId, request.Password)
	if err != nil {
		// 失败，显示错误提示
		response.Unauthorized(c, "登录失败")
	} else {
		token := jwt.NewJWT().IssueToken(user.GetStringID(), user.Name)
		response.Data(c, gin.H{
			"access_token": token,
		})
	}
}

// RefreshToken 刷新 Access Token
func (lc *LoginController) RefreshToken(c *gin.Context) {
	token, err := jwt.NewJWT().RefreshToken(c)

	if err != nil {
		response.Error(c, err, "令牌刷新失败")
	} else {
		response.Data(c, gin.H{
			"access_token": token,
		})
	}
}
